package org.yzhang3.data.utils;

import org.yzhang3.data.common.Constants;

public class BinaryUtils {

	/**
	 * parse binary chain, like '1100110000111100', to integers
	 * @param binaryChain
	 * @param bytes
	 */
	public static byte[] parseBinaryChainToBytes(StringBuilder binaryChain) {
		int i=0;
		String byteStr = null;
		byte[] bytes = new byte[binaryChain.length()/Constants.BITS_PRE_BYTE];
		while (binaryChain.length() >= Constants.BITS_PRE_BYTE) {
			byteStr = binaryChain.substring(0, Constants.BITS_PRE_BYTE);
			bytes[i++] = IntegerUtils.toByte(toInt(byteStr));
			binaryChain.delete(0, Constants.BITS_PRE_BYTE);
		}
		return bytes;
	}
	
	/**
	 * Convert the <code>target</code> to one integer.<br>
	 * <b>NOTE: </b> <code>target</code>'s length must be less than 32.
	 * @param s
	 * @return
	 */
	public static int toInt(String target) {
		byte[] bs = target.getBytes();
		int result = 0;
		int len = bs.length;
		for (int i=0; i<len; i++) {
			result = result + ((int) bs[i] - 48) * Constants.BINARY_POWS[len - 1 - i];
		}
		
		if (0 > result) {
			result = result + 1;
		}
		
		return result;
	}
	
}
